import { createSlice } from "@reduxjs/toolkit";
import todolist from "../../utile/todo";


let slice=createSlice({
  name:'todo',
  initialState:[],
  reducers:{
    init:(state,action)=>{
      state.push(...action.payload)
    },
    updata:(state,action)=>{
      // console.log(state);
       state.map(item=>{
        if (action.payload.id===item._id) {
           item.done=action.payload.done
        }else{
          return state
        }
      })
     
    },
    deltodo:(state,action)=>{
      state=state.filter(item=>{
        return item._id!==action.payload
      })
    }
  }
})

export let {init,updata } =slice.actions

let reducer=slice.reducer

export let asyncGetTodoList=()=>{
  return async dispatch=>{
    let {data} =await todolist({
      method:'get',
      url:'/todos'
    })
    dispatch(init(data))
    // console.log(data);
  }
}

export let asyncUpdaTodo=(id,done)=>{
  return async dispatch=>{
    await todolist({
      method:'post',
      url:'/dos',
      data:{id,done}
    })
    // console.log(data);
    dispatch(updata({id,done}))
  }
}


export default reducer